package com.kaiwukj.android.ufamily.mvp.ui.adapter;

import android.content.Context;
import android.util.SparseBooleanArray;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.ComplainType;

import java.util.List;

/**
 * @author Charles
 * @date 2019/8/14.
 * description：Kaiwu
 */
public class TypeAdapter extends BaseQuickAdapter<ComplainType, BaseViewHolder> {

    private Context mContext;
    private OnSelectedListener onSelectedListener;
    private SparseBooleanArray sparseBooleanArray;
    private int lastSelectPosition = -1;

    public TypeAdapter(Context context, int layoutResId, @Nullable List<ComplainType> data) {
        super(layoutResId, data);
        this.mContext = context;
        sparseBooleanArray = new SparseBooleanArray();
    }

    public void check(int pos) {
        if (pos == lastSelectPosition) return;
        if (lastSelectPosition != -1) {
            sparseBooleanArray.put(lastSelectPosition, false);
            notifyItemChanged(lastSelectPosition);
        }
        lastSelectPosition = pos;
        sparseBooleanArray.put(pos, true);
        notifyItemChanged(lastSelectPosition);
        if (onSelectedListener != null)
            onSelectedListener.onSelected(getItem(lastSelectPosition).getId());
    }

    @Override
    protected void convert(BaseViewHolder helper, ComplainType item) {
        TextView textView = helper.getView(R.id.tv_type);
        textView.setText(item.getTypeName());
        textView.setSelected(sparseBooleanArray.get(helper.getAdapterPosition()));
        textView.setOnClickListener(view -> check(helper.getAdapterPosition()));
    }

    public interface OnSelectedListener {
        void onSelected(int id);
    }

    public void setOnSelectedListener(OnSelectedListener onSelectedListener) {
        this.onSelectedListener = onSelectedListener;
    }
}
